﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

namespace API.Controllers
{
    /// <summary>
    /// 测试接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns>发达省份的</returns>
        [HttpGet]
        [Authorize]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }


        /// <summary>
        /// 登陆
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> JwtLogin()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "张三"),
                new Claim("FullName", "sunyuliang"),
                new Claim(ClaimTypes.Role, "Administrator")
            };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("中华人民共和国中华人民共和国"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                "www",
                "www",
                claims,
                DateTime.Now,
                DateTime.Now.AddMinutes(30),
                creds
                );
            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });;
        }
        /// <summary>
        /// 登陆
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> Login()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "孙余亮"),
                new Claim("FullName", "sunyuliang"),
                new Claim(ClaimTypes.Role, "Administrator")
            };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(principal, new AuthenticationProperties()
            {
                IsPersistent =true,
                AllowRefresh = true,
                ExpiresUtc = DateTimeOffset.Now.AddMinutes(60),
                RedirectUri = null
            }
             ); ;
            return "登陆成功";
        }

        /// <summary>
        /// 退出登陆
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public  ActionResult<string> LoginOut()
        {
            HttpContext.SignOutAsync().Wait();
            return "退出成功";
        }

        /// <summary>
        /// 查看登陆用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<string> ShowUserInfo()
        {
            StringBuilder sb = new StringBuilder();
            foreach(var c in HttpContext.User.Claims)
            {
                sb.Append($"{c.Type}:{c.Value}<br/>\r\n");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 根据ID获取 
        /// </summary>
        /// <param name="id">具体的ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
